<%@ page import="com.deepai.dprsmgr.utils.ErrCode" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@include file="../base_path.jsp" %>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="description" content="">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>/lib/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen"
          href="<%=basePath%>/lib/jqgrid/5.2.1/css/ui.jqgrid-bootstrap.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/lib/lobibox/css/lobibox.min.css"/>
    <link type="text/css" rel="stylesheet"
          href="<%=basePath%>/lib/bootstrap-switch/css/bootstrap3/bootstrap-switch.min.css"/>
    <link type="text/css" rel="stylesheet" href="<%=basePath%>/lib/bootstrap-select/css/bootstrap-select.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/css/mycss.css"/>

    <title>业务管理</title>
    <style>
        .header-right {
            position: absolute;
            bottom: 16px;
            right: 0px;
            top: 0px;
        }

        .page-header {
            position: relative;
        }

        .block-head {
            position: relative;
            line-height: 66px;
            font-size: 15px;
            color: #545b66;
            height: 23px;
            display: inline-block;
        }

        .head-search {

            right: 2px;
            width: 280px;
            height: 36px;
            border-radius: 5px;
            border: 1px solid #bcbec5;
            border: 1px solid #e8eaf3;
            background: #e8eaf3;
        }

        .head-search.empty_input input {
            height: 34px;
            width: 240px;
            border: none;
            border-radius: 5px;
            padding-left: 10px;
            color: #757b84;
            font-size: 14px;
            background: transparent;
        }

        .head-search input {
            height: 34px;
            width: 206px;
            border: none;
            border-radius: 5px;
            padding-left: 10px;
            color: #757b84;
            font-size: 14px;
            background: transparent;
        }

        .search-btn {
            float: right;
            width: 26px;
            height: 34px;
            padding: 8px;
            cursor: pointer;
            padding-left: 0px;
        }

        .clear-btn {
            float: right;
            width: 26px;
            height: 34px;
            padding: 8px;
            cursor: pointer;
            padding-left: 0px;
        }

        .empty_input .clear-btn {
            display: none;
        }

		/* popover样式 */
		.popover {
		    position: absolute;
		    top: 0;
		    left: 0;
		    z-index: 1060;
		    display: none;
		    max-width: 276px;
		    padding: 1px;
		    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
		    font-size: 14px;
		    font-style: normal;
		    font-weight: 400;
		    line-height: 1.42857143;
		    text-align: left;
		    text-align: start;
		    text-decoration: none;
		    text-shadow: none;
		    text-transform: none;
		    letter-spacing: normal;
		    word-break: normal;
		    word-spacing: normal;
		    word-wrap: normal;
		    white-space: normal;
		    background-color: #fff;
		    -webkit-background-clip: padding-box;
		    background-clip: padding-box;
		    border: 1px solid #6097fe;
		    /* border: 1px solid rgba(0,0,0,.2); */
		    border-radius: 6px;
		    -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
		    box-shadow: 0 5px 10px rgba(0,0,0,.2);
		    line-break: auto;
			background:#6097fe;
		}

		.popover.left>.arrow:after {
		    right: 1px;
		    bottom: -10px;
		    content: " ";
		    border-right-width: 0;
		    border-left-color: #6097fe;
		}

		.popover h5 {
			color: #FFF;
		}

    </style>
</head>
<body>
<div class="navbar-fixed-top">
    <div class="breadcrumb" style="margin-bottom: 0;">
        <span>业务中心</span>/
        <span class="active">业务管理</span>
        <span class="pull-right" title="刷新">
            <div class="btn-refresh" onclick="location.replace(location.href);">
            	<img src="<%=basePath%>/images/refresh.png" >
            </div>
        </span>

    </div>
</div>

<div class="container-fluid">
	<div class="container-fluid-main">
        <div class="page-header">
            <h3>业务管理</h3>
            <div class="header-right">

                <shiro:hasPermission name="yewuchuangjian">
                    <button class="btn btn-primary" id="btn_create_business">创建业务</button>
                </shiro:hasPermission>
                <c:choose>
                    <c:when test="${exportListSwitch == true}">
                        <button class="btn btn-primary" id="btn_export_business_list">导出业务列表</button>
                    </c:when>
                </c:choose>
            </div>

        </div>
		 <div class="page-header">
		   <div class="head-search empty_input">
		       <input type="text" placeholder="请输入业务名称关键字" id="find" autocomplete="off">
		       <img src="<%=basePath%>/images/image/sousuo.png" alt="" class="search-btn">
		       <img src="<%=basePath%>/images/image/clear.png" alt="" class="clear-btn">
		   </div>

		</div>

		<table id="businessMGRJQGrid"></table>
		<div style="height: 40px" id="businessMGRJQGridPager"></div>
	</div>


    <!-- 模态框（Modal） -->
    <div class="modal fade" id="modal_create_business" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">

            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootbox/bootbox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>
<!--/_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-switch/js/bootstrap-switch.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/i18n/defaults-zh_CN.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/jquery.validate_1.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/messages_zh.js"></script>
<!--请在下方写此页面业务相关的脚本-->

<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<script type="text/javascript">
    var keyword = '';
    $(function () {
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = "Bootstrap";
        $("#businessMGRJQGrid").jqGrid({
            height: 434,
            autowidth: true,
            shrinkToFit: true, /*  autoScroll: false, *//*forceFit: true, */
            colNames: ["主键", "业务名称", "所属组织", "业务模板", "业务描述", "黑名单", "状态", "创建时间", "更新时间", "操作人", "操作"],
            colModel: [
                {name: "business_id", index: "business_id", key: true, hidden: true},
                {
                    name: "business_name",
                    index: "business_name",
                    align: "left",
                    editable: true,
                    editrules: {required: true}
                },
                {name: "org_name", index: "org_name", align: "left"},
                {name: "template_code", index: "template_code", align: "left"},
                {name: "business_desp", index: "business_desp", align: "left", editable: true},
                {name: "check_blacklist", index: "check_blacklist", align: "left", width: 60, hidden: true},
                {name: "status", index: "status", align: "left", hidden: true},
                {name: "create_time", index: "create_time", autowidth: true, align: "left"},
                {name: "update_time", index: "update_time", autowidth: true, align: "left"},
                {name: "u_name", index: "u_name", autowidth: true, align: "left"},
                {
                    name: "edit", index: "edit", align: "center", width: 200, hidden: function () {
                        <shiro:hasPermission name="caozuoyewu">
                        return false
                        </shiro:hasPermission>
                        return true
                    }()
                }
            ],
            pager: "#businessMGRJQGridPager",
            viewrecords: true,
            hidegrid: false,
            multiselect: false,
            url: "<%=basePath%>/business/fetchBusinessMgrJQGridData.do",
            datatype: 'json',
            mtype: "POST",
            rownumbers: true,
            rownumWidth: 100,
            rowNum: 30,
            rowList: [15, 30, 50],
            jsonReader: {
                root: "dataList", page: "currPage", total: "totalPages",          //   很重要 定义了 后台分页参数的名字。
                records: "totalCount", repeatitems: false, id: "business_id"
            },
            loadComplete: function (data) {
                // 自动调整高度
                var resCount = data.records;
                var tableHeight = resCount * 30 + 40;
                $("#gbox_businessMGRJQGrid .ui-jqgrid-bdiv").css(
                    "cssText",
                    "height: " + tableHeight + "px!important;");
            },
            gridComplete: function () {         // 数据加载完成后 添加 采购按钮
                $("#businessMGRJQGrid").jqGrid('setLabel', 'rn', '序号', {
                    'text-align': 'center',
                    'font-size': '12px'
                }, '');
                var ids = jQuery("#businessMGRJQGrid").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    var rowData = jQuery("#businessMGRJQGrid").jqGrid('getRowData', id);
//                    var checkBlacklistHtml = "";
//                    if (rowData.check_blacklist == 0) {
//                        checkBlacklistHtml = "<span class='label label-default'>否</span>";
//                    } else {
//                        checkBlacklistHtml = "<span class='label label-primary'>是</span>";
//                    }
//                    jQuery("#businessMGRJQGrid").jqGrid('setRowData', ids[i], {check_blacklist: checkBlacklistHtml});
                    var statusHtml = "";
                    var editBtn = "<button type='button' class='edit btn btn-link btn-xs'  onclick='editBusiness(this, " + id + ")' style='margin-right: 2px'>编辑</button>" +
                        "<button type='button' class='save btn btn- link btn-xs hidden' onclick='saveBusiness(this, " + id + ")' style='margin-right: 2px' >保存</button>" +
                        "<button type='button'  class='cancel btn btn-link btn-xs hidden' onclick='cancelBusiness(this," + id + ")' style='margin-right: 2px' >取消</button>"
                    if (rowData.status == 1) {
                        statusHtml = "<span class='label label-success'>已启用</span>";
//                        editBtn += "<button type='button' class='btn btn-link btn-xs' style='margin-left: 2px' " +
//                            "onclick='businessDisable(this, " + id + ")'>停用</button>"
                    } else if (rowData.status == 2) {
                        statusHtml = "<span class='label label-default'>已停用</span>";
//                        editBtn += "<button type='button' class='btn btn-link btn-xs' style='margin-left: 2px' " +
//                            "onclick='businessEnable(this, " + id + ")'>启用</button>"
                    }
//                    var infoHtml= "<button type='button' class='btn btn-link btn-xs' style='margin-left: 2px' " +
//                        "data-container='body' data-toggle='popover' data-placement='left' data-content='暂无内容' " +
//                        "onclick='taskStatistic(this, " + id + ")'>任务统计</button>";
                    jQuery("#businessMGRJQGrid").jqGrid('setRowData', ids[i], {status: statusHtml});
                    jQuery("#businessMGRJQGrid").jqGrid('setRowData', ids[i], {edit: editBtn});
//                    jQuery("#businessMGRJQGrid").jqGrid('setRowData', ids[i], {info: infoHtml});

                }
            },
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
                return (cm[i].name != 'edit');
            },
            onSelectRow: function (rowid) {
//                showTaskInfo(rowid);
            },
            ondblClickRow: function (id) {
                <%--$("#modalCallInfo").modal({--%>
                <%--remote: '<%=basePath %>/call/callInfoShow.do?reserve_id=' + id--%>
                <%--});--%>
//                if (id && id !== lastSel) {
//                    jQuery('#blacklistJQGrid').jqGrid('restoreRow', lastSel);
//                    jQuery('#blacklistJQGrid').jqGrid('editRow', id, true);
//                    lastSel = id;
//                }
            },
            editurl: "<%=basePath %>/business/businessEdit.do"

        });

        $("#btn_create_business").click(function () {
            $("#modal_create_business").modal({
                backdrop: false,
                keyboard: false,
                remote: '<%=basePath %>/business/showCreateBusinessPage.do'
            });
        });

        $("#modal_create_business").on("hidden.bs.modal", function () {
            $(this).removeData("bs.modal");
            $(this).find(".modal-content").children().remove();
            refreshJQGrid();
        });

        $("#btn_export_business_list").click(function () {
            var data = $("#businessMGRJQGrid").jqGrid('getRowData');
            if (data.length == 0) {
                myNotify("warning", "", "暂无数据可导出！");
            } else {
                window.location.href = "<%=basePath%>/business/exportBusinessListExcel.do?keyword=" + keyword;
            }
        });

        $(document).on('keydown', 'body,#find', function (evt) { //回车发送
            evt.stopPropagation();
            var e = evt || event;
            if (e.keyCode === 13 && $('#find').is(':focus')) {
                search()
            }
        });
        $('.search-btn').click(function () {
            search();
        });

        $('.clear-btn').click(function () {
            keyword = "";
            $('#find').val('');
            $('.head-search').addClass('empty_input');
            search();
        });

        $("#find").on("input propertychange change", function (e) {
            var val = $(this).val();
            if (val) {
                $('.head-search').removeClass('empty_input');
            } else {
                $('.head-search').addClass('empty_input');
            }
        })
    });


    /******************************方法声明**********************************/
    /**
     * 刷新表格数据
     */
    function refreshJQGrid() {
        var postData = {};
        postData.keyword = $("#find").val().trim();
        keyword = postData.keyword;
        $("#businessMGRJQGrid").jqGrid("setGridParam", {
            url: "<%=basePath %>/business/fetchBusinessMgrJQGridData.do",
            mtype: 'POST',
            datatype: "json",
            postData: postData
        }).trigger("reloadGrid");
    }

    function search() {
        refreshJQGrid();
    }

    function businessDisable(obj, id) {
        bootbox.confirm({
            message: "停用后该业务下的所有任务将会终止，但外呼数据会保留，是否继续？",
            buttons: {
                confirm: {
                    label: '确认',
                    className: 'btn-success'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-danger'
                }
            },
            callback: function (result) {
                if (result) {
                    var command = "disable";
                    $.ajax({
                        url: "<%=basePath%>/business/checkBusinessTask.do",
                        type: "post",
                        async: true,
                        data: "businessId=" + id + "&command=" + command,
                        dataType: "json",
                        success: function (data) {
                            if (data["errorCode"] == "0") {
//                                myNotify("success", "", data["msg"]);
                                businessOperate(obj, id, command);
//                                refreshJQGrid();
                            } else if (data["errorCode"] == "<%=ErrCode.BUSINESS_ERR_CODE_STOP%>") {
                                bootbox.confirm({
                                    message: "任务正在外呼，停用此业务任务将终止执行，是否继续？",
                                    buttons: {
                                        confirm: {
                                            label: '确认',
                                            className: 'btn-success'
                                        },
                                        cancel: {
                                            label: '取消',
                                            className: 'btn-danger'
                                        }
                                    },
                                    callback: function (result) {
                                        if (result) {
                                            var command = "disable";
                                            businessOperate(obj, id, command);
                                        }
                                    }
                                });
                            } else if (data["errorCode"] == "<%=ErrCode.BUSINESS_ERR_CODE_ENABLE_FAILED%>") {
                                myNotify("error", "", "");  /*业务模板检验*/
                            }
                        },
                        error: function (data) {
                            myNotify("error", "", "操作请求发送过程中发生错误，请尽快联系管理员！");
                        }
                    });
                    //businessOperate(obj, id, command);
                }
            }
        });

    }

    function businessEnable(obj, id) {
        bootbox.confirm({
            message: "启用后该业务下的所有任务不会启动，是否继续？",
            buttons: {
                confirm: {
                    label: '确认',
                    className: 'btn-success'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-danger'
                }
            },
            callback: function (result) {
                if (result) {
                    var command = "enable";
                    $.ajax({
                        url: "<%=basePath%>/business/checkBusinessOrgStatus.do",
                        type: "post",
                        async: true,
                        data: "id=" + id + "&command=" + command,
                        dataType: "json",
                        success: function (data) {
                            if (data["errorCode"] == "0") {
                                // myNotify("success", "", data["msg"]);
                                businessOperate(obj, id, command);
//                                refreshJQGrid();
                            } else {
                                myNotify("error", "", "该组织已停用，无法启用该业务，若要启用，请先启用组织！");
                            }
                        },
                        error: function (data) {
                            myNotify("error", "", "操作请求发送过程中发生错误，请尽快联系管理员！");
                        }
                    });
                   // businessOperate(obj, id, command);
                }
            }
        });
    }

    function businessOperate(obj, id, command) {
        $.ajax({
            url: "<%=basePath%>/business/businessOperate.do",
            type: "post",
            async: true,
            data: "id=" + id + "&command=" + command,
            dataType: "json",
            success: function (data) {
                if (data["errorCode"] === "0") {
                    myNotify("success", "", data["msg"]);
                    refreshJQGrid();
                } else {
                    myNotify("error", "", data["msg"]);
                }
            },
            error: function (data) {
                myNotify("error", "", "操作请求发送过程中发生错误，请尽快联系管理员！");
            }
        });
    }

    function cancelBusiness(obj, id) {
        $('#businessMGRJQGrid').restoreRow(id);
        $("#businessMGRJQGrid #" + id).find(".save,.cancel").addClass("hidden");
        $("#businessMGRJQGrid #" + id).find(".edit").removeClass("hidden");
    }

    // 编辑业务名称
    function editBusiness(obj, id) {
        var editNum = $('input[name="business_name"]').length;
        if (editNum == 0) {//当前没有编辑状态的行
            editId = id;
            $(obj).addClass("hidden");
            $(obj).parent().children(".save,.cancel").removeClass("hidden");
            $("#businessMGRJQGrid").jqGrid("editRow", id);
        } else {
            myNotify("warning", "", "请先保存之前编辑的信息！");
        }
    }

    // 保存业务名称
    function saveBusiness(obj, id) {
        var reg = /^[\w\u4e00-\u9fa5]+$/;
        var businessName = $.trim($(obj).parent().siblings().eq(2).find("input[name='business_name']").val());
        var check = CheckName(businessName, true, false, true);
        var businessComment = $.trim($("#" + id + '_business_desp').val());
        var regComment = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ,，。._]/g;
        //验证业务名称
        if (!check.pass) {
            myNotify("error", "", "业务名称" + check.msg);
            return false;
        }

        if (!checkBusinessNameUnique(id, businessName)) {
            myNotify("error", "", "业务名称已存在，请重新输入");
            return false;
        }

        if (regComment.test(businessComment)) {
            myNotify("error", "", "备注有特殊字符，只能包含中文、英文、数字、下划线、逗号、句号");
            return false;
        }

        if (businessComment.length > 80) {
            myNotify("error", "", "备注最多输入80个字");
            return false;
        }

        $("#businessMGRJQGrid").jqGrid("saveRow", id, onSaveResponse);
    }

    // 处理响应结果
    function onSaveResponse(response) {
        if (response.responseText == "0") {
            myNotify("success", "", "保存成功！");
        } else if (response.responseText == "3111") {
            myNotify("error", "", "业务名称已经存在！");
            return;
        } else {
            myNotify("error", "", "保存失败！");
        }
        refreshJQGrid();
    }


    <%--function taskStatistic(obj, id) {--%>
        <%--$.ajax({--%>
            <%--url: "<%=basePath%>/task/statisticTaskByBusiness.do",--%>
            <%--type: "post",--%>
            <%--async: true,--%>
            <%--data: "business_id=" + id,--%>
            <%--dataType: "json",--%>
            <%--success: function (data) {--%>
                <%--console.log(data)--%>
                <%--var statisticResult = "<h5>总任务数：" + data.map.total_task_cnt + "</h5>" +--%>
                    <%--"<h5>任务完成数：" + data.map.finish_task_cnt + "</h5>" +--%>
                    <%--"<h5>任务未完成数：" + data.map.remain_task_cnt + "</h5>" +--%>
                    <%--"<h5>呼叫完成数：" + data.map.finish_call_cnt + "</h5>" +--%>
                    <%--"<h5>呼叫未完成数：" + data.map.remain_call_cnt + "</h5>";--%>
                <%--$(obj).attr("data-content", statisticResult);--%>
                <%--$(obj).popover({html: true});--%>
            <%--},--%>
            <%--error: function (data) {--%>
                <%--myNotify("error", "", "操作请求发送过程中发生错误，请尽快联系管理员！");--%>
            <%--}--%>
        <%--});--%>
    <%--}--%>

    function checkBusinessNameUnique(id, name) {
        var checkBusinessNameUrl = "<%=basePath%>/business/checkEditBusinessNameUniqueness.do";
        var flag;
        $.ajax({
            url: checkBusinessNameUrl,
            type: "post",
            async: false,
            data: {
                businessId: id,
                type: 1,
                businessName: name,
            },
            dataType: "json",
            success: function (data) {
                if (data.errorCode == "0") {
                    flag = true;
                } else {
                    flag = false;
                }
            },
            error: function (data) {
                myNotify("error", "", "向服务器发送删除请求过程中发生错误！");
            }
        });

        return flag
    }

</script>
</body>
</html>